<?php
global $dPconfig;
$task_id = intval( dPgetParam( $_REQUEST, 'task_id', 0 ) );

if ($_POST['save'] != '') {

	/*
	$sd = new CDate($_POST['task_start_date'].'080000');
	$sd = $sd->format(FMT_DATETIME_MYSQL);
	$ed = '';
	if (isset($_POST['task_end_date']) && $_POST['task_end_date'] != '') {
		$ed = new CDate($_POST['task_end_date'] . '180000');
		$ed = $ed->format(FMT_DATETIME_MYSQL);
	}

	$task_name = htmlentities(stripslashes($_POST['task_name']), ENT_QUOTES);
	$task_dynamic = isset($_POST['task_dynamic']) ? 1 : 0;
	$task_milestone = isset($_POST['task_milestone']) ? 1 : 0;
	$task_status = isset($_POST['task_status']) ? 0 : -1;
	$task_creator = isset($_POST['task_creator']) ? $_POST['task_creator'] : $AppUI->user_id;

	$q = new DBQuery;
	$q->addTable('tasks');
	$values = array(
		$task_name,
		$_POST['task_parent'], $_POST['task_project'], $task_creator,
		$sd, $_POST['task_duration'], 1, $ed,
		htmlentities(stripslashes($_POST['task_description']), ENT_QUOTES),
		$_POST['task_priority'], $task_creator, 0, 0,
		$task_dynamic, 0, 0, 0, $task_milestone, $task_status
	);
	$fields = 'task_name,task_parent,task_project,task_owner,'.
		'task_start_date,task_duration,task_duration_type,task_end_date,task_description,'.
		'task_priority,task_creator,task_order,task_client_publish,'.
		'task_dynamic,task_access,task_notify,task_type,task_milestone,task_status';
	if ($task_id <= 0) {
		$q->addInsert($fields, $values, true);
		$AppUI->setMsg( 'Task <br/>['.$task_name.']<br/>has been added', UI_MSG_OK);
	}
	else {
		$q->addUpdate($fields, $values, true);
		$q->addWhere('task_id = '.$task_id);
		$AppUI->setMsg( 'Task <br/>['.$task_name.']<br/>has been updated', UI_MSG_OK);
	}
	$q->exec();

	if ($task_id <= 0) {
		$q->clear();
		$q->addTable('tasks');
		$q->addQuery('task_id');
		$q->addWhere('task_name = "'.$task_name.'"');
		$q->addWhere('task_project = '.$_POST['task_project']);
		$q->addWhere('task_creator = '.$AppUI->user_id);
		$task_id = $q->loadResult();
	}

	db_exec('DELETE FROM user_tasks WHERE task_id = '.$task_id);
	if (is_array($_POST['task_members']))
	foreach ($_POST['task_members'] as $uid) {
		$cval = $_POST['contribute_'.$uid];
		$q = 'INSERT INTO '.
				'user_tasks(user_id,user_type,task_id,perc_assignment) ' .
				"values($uid, 0, $task_id, $cval)";
		db_exec($q);
	}

	db_exec('DELETE FROM task_dependencies WHERE dependencies_task_id = '.$task_id);
	if (is_array($_POST['task_predecessors']))
	foreach ($_POST['task_predecessors'] as $p) {
		db_exec("INSERT INTO task_dependencies VALUES($task_id, $p)");
	}

	if ($_POST['task_parent'] == '0') {
		db_exec("UPDATE tasks SET task_parent = $task_id WHERE task_id=$task_id");
	}
	*/

	$obj = new CTask();
	if (!$obj->bind( $_POST )) {
		$AppUI->setMsg( $obj->getError(), UI_MSG_ERROR );
		$AppUI->redirect( $AppUI->getPlace() );
	}
	else {
		 $obj->store();
		$AppUI->redirect( $AppUI->getPlace() );
	}
}

$df = $AppUI->getPref('SHDATEFORMAT');
$task_project = $_REQUEST['project_id'];
$perms =& $AppUI->acl();

// load the record data
$obj = new CTask();

// check if we are in a subform
if ($task_id > 0 && !$obj->load( $task_id )) {
	$AppUI->setMsg( 'Task' );
	$AppUI->setMsg( 'invalidID', UI_MSG_ERROR, true );
	$AppUI->redirect();
}

$task_parent = isset($_REQUEST['task_parent'])? $_REQUEST['task_parent'] : $obj->task_parent;

// check for a valid project parent
$task_project = intval( $obj->task_project );
if (!$task_project) {
	$task_project = dPgetParam( $_REQUEST, 'task_project', 0 );
	if (!$task_project) {
		$AppUI->setMsg( "badTaskProject", UI_MSG_ERROR );
		$AppUI->redirect();
	}
}

// check permissions
$msg = 'You do not have permission to edit this task';
$needCheckCostCenter = $perms->userHasRole($AppUI->user_id, 'Operation') || $perms->userHasRole($AppUI->user_id, 'FFIA_Staff');
if ( $task_id ) {
	// we are editing an existing task
	// trangdt replace
	//$canEdit = $perms->checkModuleItem( $m, 'edit', $task_id );
	$canEdit = $perms->checkModuleItem( $m, 'edit') && ($needCheckCostCenter ? $obj->task_costcenter==$AppUI->user_costcenter : TRUE);
	// trangdt end
	if (!$canEdit) {
		$msg = 'You do not have permission to edit this task';
	}
	else if ($obj->task_is_complete > 0) {
		$msg = 'Can not edit completed task';
	}
} else {
	// do we have access on this project?
	$canEdit = $perms->checkModuleItem( 'projects', 'view', $task_project );
	// And do we have add permission to tasks?
	if ($canEdit)
	  $canEdit = $perms->checkModule('tasks', 'add');
}


if (!$canEdit) {
	$AppUI->setMsg($msg, UI_MSG_ERROR);
	$AppUI->redirect();
}

//check permissions for the associated project
$canReadProject = $perms->checkModuleItem( 'projects', 'view', $obj->task_project);

$durnTypes = dPgetSysVal( 'TaskDurationType' );

// check the document access (public, participant, private)
if (!$obj->canAccess( $AppUI->user_id )) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

// pull the related project
$project = new CProject();
$project->load( $task_project );

if (!$project->canEdit()) {
	$AppUI->setMsg('Access denied', UI_MSG_ERROR);
	$AppUI->redirect();
}

$ptasks = array();

function getSpaces($amount){
	if($amount == 0) return '';
	return str_repeat('&nbsp;', $amount);
}

function constructTaskTree($task_data, $depth = 0){
	global $projTasks, $all_tasks, $parents, $task_parent_options, $task_parent, $task_id, $ptasks;

	$projTasks[$task_data['task_id']] = $task_data['task_name'];

	$selected = $task_data['task_id'] == $task_parent ? 'selected="selected"' : '';
	$task_data['task_name'] = strlen($task_data[1]) > 45 ?
		substr($task_data['task_name'],0, 45).'...' : $task_data['task_name'];

	$task_parent_options .= '<option value="'.$task_data['task_id'].'" '.$selected.'>'.
		getSpaces($depth*3).dPFormSafe($task_data['task_name']).'</option>';
	$ptasks[$task_data['task_id']] = '<img src="images/blank.gif" width="'.(12 * $depth).'" height="1"/>'.$task_data['task_name'];

	if (isset($parents[$task_data['task_id']])) {
		foreach ($parents[$task_data['task_id']] as $child_task) {
			if ($child_task != $task_id)
				constructTaskTree($all_tasks[$child_task], ($depth+1));
		}
	}
}

function build_date_list(&$date_array, $row) {
	global $tracked_dynamics, $project;
	// if this task_dynamic is not tracked, set end date to proj start date
	if ( !in_array($row['task_dynamic'], $tracked_dynamics) )
		$date = new CDate( $project->project_start_date );
	elseif ($row['task_milestone'] == 0) {
		$date = new CDate($row['task_end_date']);
	} else {
		$date = new CDate($row['task_start_date']);
	}
	$sdate = $date->format('%d/%m/%Y');
	$shour = $date->format('%H');
	$smin = $date->format('%M');

	$date_array[$row['task_id']] = array($row['task_name'], $sdate, $shour, $smin);
}

$q = new DBQuery();
$q->addTable('users', 'u');
$q->addTable('contacts', 'c');
//$q->addTable('project_contacts', 'pc');
$q->addQuery('user_id, concat(contact_first_name, \' \', contact_last_name) as contact_name');
//$q->addWhere('pc.contact_id = u.user_id AND u.user_contact = c.contact_id AND pc.project_id = '.$task_project);
$q->addWhere('u.user_contact = c.contact_id');
$q->addOrder('contact_first_name');
$sql = $q->prepare();
$resourceList = db_loadHashList($sql);
$resourceList = arrayMerge(array(''=>''), $resourceList);

require_once( $AppUI->getModuleClass( 'quotations' ) );
$quotationO = new CQuotations();

require_once($AppUI->getMasterDataClass( 'mddivision' ));
$divisionList = arrayMerge(array( '' => '' ), getDivisionList());

require_once($AppUI->getMasterDataClass( 'mdcostcenter' ));
$costcenterList = arrayMerge(array( '' => '' ), getCostCenterList());
//load item
if ($obj->task_id) {
	require_once( $AppUI->getModuleClass( 'items' ) );
	$itemO = new CItem();
	$itemO->load($obj->task_item);
	$obj->task_item_code = $itemO->item_code;

	require_once( $AppUI->getMasterDataClass( 'mdtype' ) );
	$typeO = new CMdType();
	$typeO->load($itemO->item_type1);
	$obj->task_item_type = $typeO->name;
}

$dtasks = array();
$members = array();
if ($task_id > 0) {
	$sql = 'SELECT * FROM user_tasks WHERE task_id = '.$task_id;
	$members = db_loadHashList($sql, 'user_id');

	$sql = 'SELECT * FROM task_dependencies WHERE dependencies_task_id = '.$task_id;
	$dtasks = db_loadHashList($sql, 'dependencies_req_task_id');
}
else {
	$members[$AppUI->user_id] = array('perc_assignment' => 100);
}

$q = new DBQuery();
$q->clear();
$q->addTable('holidays');
$q->addQuery('hdate,description');
$q->addOrder('hdate');
$holidays = $q->loadHashList();

// let's get root tasks
$sql = 'SELECT task_id, task_name, task_end_date, task_start_date, task_milestone, task_parent, task_dynamic
		FROM tasks
		WHERE task_project = '.$task_project.' AND task_id = task_parent
        ORDER BY task_start_date';

$root_tasks = db_loadHashList($sql, 'task_id');

$projTasks           = array();
$task_parent_options = '';

// Now lets get non-root tasks, grouped by the task parent
$sql = 'SELECT task_id, task_name, task_end_date, task_start_date, task_milestone, task_parent, task_dynamic
		FROM tasks
		WHERE task_project = '.$task_project.' AND task_id != task_parent
		ORDER BY task_start_date';

$parents = array();
$projTasksWithEndDates = array( $obj->task_id => $AppUI->_('None') );//arrays contains task end date info for setting new task start date as maximum end date of dependenced tasks
$all_tasks = array();
$sub_tasks = db_exec($sql);
if ($sub_tasks) {
	while ($sub_task = db_fetch_assoc($sub_tasks)) {
		// Build parent/child task list
		$parents[$sub_task['task_parent']][] = $sub_task['task_id'];
		$all_tasks[$sub_task['task_id']] = $sub_task;
		build_date_list($projTasksWithEndDates, $sub_task);
	}
}

// let's iterate root tasks
foreach ($root_tasks as $root_task) {
	build_date_list($projTasksWithEndDates, $root_task);
	if ($root_task['task_id'] != $task_id)
		constructTaskTree($root_task);
}

// setup the title block
$ttl = $task_id > 0 ? 'Edit Task' : 'Add Task';
$titleBlock = new CTitleBlock( $ttl );
$titleBlock->addButton( 'tasks list', 'index.php?m=tasks' );
$titleBlock->addCell();
$titleBlock->show();

//Dynamic tasks are by default now off because of dangerous behavior if incorrectly used
if ( is_null($obj->task_dynamic) ) $obj->task_dynamic = 0 ;

$can_edit_time_information = $obj->canUserEditTimeInformation();

if (intval($obj->task_start_date))
	$start_date = new CDate($obj->task_start_date);
else if ($task_id != 0)
	$start_date = null;
else
	$start_date = new CDate();

$end_date = intval( $obj->task_end_date ) ? new CDate( $obj->task_end_date ) : new CDate();
$task_creator = isset($obj->task_creator) ? $obj->task_creator : $AppUI->user_id;

// Load all item list
require_once($AppUI->getModuleClass('items'));
$iO = new CItem();
$itemList = $iO->getItemsList4AutoCompleter('TaskItem');

//prepare list for quotatation list
$taskList = '';
foreach ($itemList as $p) {
	$id = $p->id;
	$q = new DBQuery();
	$q->addTable('quotation_lines');
	$q->innerJoin('items', 'i', 'qitem_item = item_id');
	$q->innerJoin('quotations', 'q', 'qitem_quotation = quote_id');
	$q->addWhere("quote_customer = {$project->project_company}");
	$q->addWhere("quote_currency = {$project->project_currency}");
	$q->addWhere("quote_completed = 1");
	$q->addWhere("qitem_item = {$id}");
	$q->addQuery('quote_id, quote_code, quote_name, quote_version, quote_start_date, quote_expire_date');
	$tasks = $q->loadHashList('quote_id');
	if (count($tasks) > 0) {
		$taskList .= '['.$id.',';
		foreach ($tasks as $zid => $t) {
			$sd = new CDate($t['quote_start_date']);
			$ed = new CDate($t['quote_expire_date']);
			$sd = $sd->format("%m %d, %Y");
			$ed = $ed->format("%m %d, %Y");
			$taskList .= '['.$zid.',"'.'['.addslashes(html_entity_decode($t['quote_code'])).'] '.addslashes(html_entity_decode($t['quote_name'])).'", ' . intval($t['quote_version']).', "' . $sd . '"' . ', "' . $ed . '"'  . '],';
		}
		$taskList .= '0],'."\n";
	}
}
$quotationList = array(''=>'-');//tmp list for first load
/*$confirmed = dPgetSysVal('QuotationConfirmed');
$objMD = new CMdStatus();
$objMD->loadByCode($confirmed['code']);
$result = $quotationO->getListQuotationByCusId($uid, $objMD->status_id, $project->project_company);
$quotationList = array( 0 => '');
foreach($result as $q) {
	$quotationList[$q['quote_id']] = "[" . $q['quote_code'] . "] " . $q['quote_name'];
}*/

// Load list unit
require_once($AppUI->getMasterDataClass('mdunit'));
$unitObj = new CMdUnit();
$unitList = $unitObj->loadAllUnit();

?>
<script language="JavaScript">
Calendar.enabled = true;

function doCancel() {
	go('?m=projects&a=view&project_id=' + <?=$task_project?>);
}

function doCheckSubmit()
{
	var t = $('idTaskName');
	if (t.value.trim() == '') {
		t.focus();
		alert('Missing task name');
		return false;
	}
	var d = $('idDuration');
	if (d.value.trim() == '') {
		doCalcDuration();
	}
	return true;
}

function doSelectItem(itemObj) {
	if(itemObj==null){
		$('task_item_id').value = '';
		$('task_item_autocompleter').value = '';
		$('idTaskItemName').value = '';
		$('idTaskItemType').value = '';
	}
	else{
		$('task_item_id').value = itemObj.id;
		$('task_item_autocompleter').value = itemObj.code;
		$('idTaskItemName').value = itemObj.name;
		$('idTaskItemType').value = itemObj.type;
		//$('idTaskVolumeUnit').value = itemObj.volume;
		//$('idTaskWeightUnit').value = itemObj.weight;
		//$('idTaskQuantityUnit').value = itemObj.quantity;

		changeProject(itemObj.id);
	}
}

var taskList = [<?=$taskList?>];

function changeProject(selValue) {
	var pid = selValue;
	var t = $('task_quotation');

	t.options.length = 0;
	var fd = Date.parseDate($('idDateFrom').value, '<?=FMT_TIMESTAMP_DATE?>');
	for (i in taskList) {
		if (taskList[i] == 0) return;
		var p = taskList[i];
		if (p[0] == pid) {
			var n = 0;
			t.options[n++] = new Option('-', '');
			for (z = 1; p[z] != 0; z++) {
				var sd = new Date(p[z][3]);
				var ed = new Date(p[z][4]);
				if (fd < sd || fd > ed) {
					continue;
				}
				var opt = new Option(p[z][1], p[z][0]);
				t.options[n++] = opt;
				opt.setAttribute('percent', p[z][2]);
			}
			break;
		}
	}
}

function changeQuotation(sel, tid) {
	if (typeof(tid) != 'undefined') {
		for (var i = 0; i < sel.options.length; i++)
			if (sel.options[i].value == tid) {
				sel.selectedIndex = i;
				break;
			}
	}
}
</script>
<form name="SimpleTaskEditForm" action="?m=tasks&a=simpleaddedit&project_id=<?=$task_project?>" method="post"
	onsubmit="return doCheckSubmit()">
	<input name="task_id" type="hidden" value="<?=$task_id?>" />
	<input type="hidden" name="dosql" value="do_task_aed" />
	<input name="task_project" type="hidden" value="<?=$task_project?>" />
	<input name="task_creator" type="hidden" value="<?=$task_creator?>" />
	<input name="task_percent_complete" type="hidden" value="<?=$obj->task_percent_complete?>"/>
	<input name="task_is_complete" type="hidden" value="<?=$obj->task_is_complete?>"/>
	<input name="task_status" type="hidden" value="0"/>
	<input name="task_quotation_version" id="task_quotation_version" type="hidden" value="<?=@$obj->task_quotation_version?>"/>
<table border="0" cellpadding="4" cellspacing="0" width="100%">
<tr>
	<td class="tabon">[&nbsp;<?=$project->project_iso_code?>&nbsp;]&nbsp;<?=$project->project_name?></td>
	<td width="100%">&nbsp;</td>
</tr>
</table>
<table border="0" cellpadding="4" cellspacing="0" width="100%" class="infopanel">
<tr>
	<td nowrap="nowrap">
		<input class="button" type="submit" name="save"
				value="<?=$AppUI->_('save')?>"/>
		<input class="button" type="submit" name="save_new"
				value="<?=$AppUI->_('save & new')?>"/>
		<input class="button" type="button" name="cancel"
				value="<?=$AppUI->_('cancel')?>" onClick="doCancel()" />
	</td>
	<td align="right" width="100%">
	<?php
		if ($canReadProject) {
			showButton( 'view this reference', '?m=projects&a=view&project_id='.$task_project );
		}
		if ($task_id > 0) {
			showButton( 'view this task', '?m=tasks&a=view&task_id='.$obj->task_id );
		}
	?>&nbsp;
	</td>
</tr>
</table>
<table border="0" cellpadding="10" cellspacing="4" width="100%" class="subinfopanel">
<tr>
<td width="580px" valign="top" id="idColumnLeft">
<table border="0" cellpadding="0" cellspacing="4" >
<tr>
	<td align="right" nowrap="nowrap">* <?=$AppUI->_('Item code');?></td>
	<td colspan="3" nowrap>
		<?= arrayAutoSelectLocalItem($itemList, 'task_item', 'style="width: 280px" maxlength="255"', @$obj->task_item, false, @$obj->task_item_code, 'doSelectItem');?>
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap">* <?=$AppUI->_('Task name');?></td>
	<td colspan="3">
		<input id="idTaskItemName" type="text" class="text" name="task_name"
			value="<?=$obj->task_name?>" style="width: 300px" maxlength="255" title="Task name :: Task name is required. It will automaitcal fill after selecting item code"/>
	</td>
</tr>
<tr>
	<td align="right"><?=$AppUI->_('Item type');?></td>
	<td colspan="3">
		<input id="idTaskItemType" type="text" class="text" name="task_item_type"
			value="<?=$obj->task_item_type?>" style="width: 300px" maxlength="255" readonly="true" title="Item type :: Item type will automaitcal fill after selecting item code"/>
	</td>
</tr>
<tr>
	<td align="right">* <?=$AppUI->_('Quantity');?></td>
	<td nowrap="nowrap">
		<input id="idTaskFigure" type="text" class="text" name="task_figure" onkeyup="return (currencyFormat(this, ',', '.', event))"
			value="<?=number_format($obj->task_figure, 2)?>" style="width: 100px; text-align: right" maxlength="30" autocomplete="off"/>
	</td>
	<td align="right" nowrap>
		* <?=$AppUI->_('Unit');?>
	</td>
	<td>
		<?php
			//	print_r($obj);
			$tmp_unit_type = 0;
			$unitList_len = count($unitList);
			$unitType_sel = @$obj->task_unit;
			echo "<select id='idTaskUnit' name='task_unit' class='text' style='text-transform: capitalize; width: 140px;'>";
			echo "<option value=''>{$AppUI->_('Select One')}</option>";
			for($i = 0; $i < $unitList_len; $i++){
				if($tmp_unit_type != $unitList[$i]['unit_type']){
					$tmp_unit_type = $unitList[$i]['unit_type'];
					echo "<optgroup label='{$unitList[$i]['type_name']}'>";
				}
				echo "<option value='".$unitList[$i]['unit_id']."'";
				if($unitType_sel and ($unitType_sel == $unitList[$i]['unit_id'])){
					echo ' selected="selected"';
				}
				echo "> {$unitList[$i]['unit_name']}</option>";
				if((($tmp_unit_type != 0) and ($tmp_unit_type != $unitList[$i]['unit_type'])) or ($i == $unitList_len)){
					echo '</optgroup>';
				}
			}
			echo "</select>";
			// arraySelect($unitList, 'task_unit', ' size="1" class="text" ', @$row->task_unit, true);
		?>
	</td>
	<?php
	/*
	<td align="right" nowrap>
		<?=$AppUI->_('Quantity unit');?>
	</td>
	<td>
		<input id="idTaskQuantityUnit" tabindex="100" type="text" readonly="true" class="text" name="task_quantity_unit"
			value="<?=@$itemO->qunit_name?>" style="width: 80px; text-align: right" maxlength="30" />
	</td>
	*/
	?>
</tr>
<?php
/*
<tr>
	<td align="right" nowrap><?=$AppUI->_('Weight unit');?></td>
	<td nowrap="nowrap">
		<input id="idTaskWeightUnit" tabindex="100" type="text" readonly="true"  class="text" name="task_weight_unit"
			value="<?=@$itemO->wunit_name?>" style="width: 100px; text-align: right" maxlength="30" />
	</td>	<td align="right">
		<?=$AppUI->_('Volume unit');?>
	</td>
	<td>
		<input id="idTaskVolumeUnit" tabindex="100" type="text" class="text" readonly="true" name="task_volume_unit"
			value="<?=@$itemO->vunit_name?>" style="width: 80px; text-align: right" maxlength="30" />
	</td>
</tr>
*/
?>
<tr>
	<td align="right" nowrap="nowrap">
		<?=$AppUI->_( 'Start date' )?>
	</td>
	<td>
		<input id="idDateFrom" type="hidden" name="task_start_date" onchange="doCheckDate(this)"
				value="<?=$start_date ? $start_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateFromD" type="text" style="width: 60px"
				value="<?=$start_date ? $start_date->format( $df ) : ''?>"
				class="text" readonly="true" title="Start date :: Start date is required"/>
		<img id="idDateFromB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>" border="0">
	</td>
	<td align="right">
		<?=$AppUI->_( 'End date' )?>
	</td>
	<td>
		<input id="idDateTo" type="hidden" name="task_end_date" onchange="doCheckDate(this)"
				value="<?=$end_date ? $end_date->format( FMT_TIMESTAMP_DATE ) : ''?>" />
		<input id="idDateToD" type="text" style="width: 60px"
				value="<?=$end_date ? $end_date->format( $df ) : ''?>"
				class="text" readonly="true" title="Finish date :: End date is required"/>
		<img id="idDateToB" src="images/calendar.gif" title="<?=$AppUI->_('Calendar')?>" border="0">
	</td>
</tr>
<tr>
	<td align="right" nowrap="nowrap"><?=$AppUI->_( 'Start time' )?></td>
	<td nowrap="nowrap">
		<input id="idStartTime" type="text" style="width: 36px; text-align: right" name="task_start_time" value="<?=$obj->task_start_time?>"/>
	</td>
	<td align="right" nowrap="nowrap"><?=$AppUI->_( 'End time' )?></td>
	<td nowrap="nowrap">
		<input id="idEndTime" type="text" style="width: 36px; text-align: right" name="task_end_time" value="<?=$obj->task_end_time?>"/>
	</td>
</tr>
<tr>
	<td align="right" valign="top">* <?=$AppUI->_('Location');?></td>
	<td colspan="3">
		<input class="text" type="text" name="task_location" id="task_location" style="width: 300px;" title="Task location :: Task location is required" value="<?=$obj->task_location?>"/>
	</td>
</tr>
</table>
</td>
<td width="100%" valign="top" id="idColumnRight">
	<table border="0" cellpadding="0" cellspacing="4" >
	<tr>
		<td align="right">* <?=$AppUI->_('Division');?></td>
		<td>
			<?=arraySelect( $divisionList, 'task_division',
				'id="idTaskDivision" class="text" style="text-transform: capitalize; width: 300px" title="Division :: Division is required"',
				$obj->task_division, true )?>
		</td>
	</tr>
	<tr>
		<td align="right" nowrap="nowrap">* <?=$AppUI->_('Cost center');?></td>
		<td>
			<?=arraySelect( $costcenterList, 'task_costcenter',
				'id="task_costcenter" class="text" style="text-transform: capitalize; width: 300px" title="Cost center :: Cost center is required"',
				$obj->task_costcenter, true )?>
		</td>
	</tr>
	<tr>
		<td align="right">* <?=$AppUI->_('Resource');?></td>
		<td>
			<?=arraySelect( $resourceList, 'task_resource',
				'id="task_resource" class="text" style="text-transform: capitalize; width: 300px" title="Resource :: Resource is required"',
				$obj->task_resource, true )?>
		</td>
	</tr>
	<tr>
		<td align="right"> <?=$AppUI->_('Quotation');?></td>
		<td>
			<?=arraySelect( $quotationList, 'task_quotation',
				'id="task_quotation" class="text" style="text-transform: capitalize; width: 300px"',
				$obj->task_quotation, true )?>
		</td>
	</tr>
	<tr>
		<td align="right" valign="top">
			<?=$AppUI->_( 'Remarks' )?>
		</td>
		<td colspan="3">
			<textarea id="task_remarks" class="text" name="task_description" style="width: 300px; height: 63px" title="Remarks :: Remarks should not be longer than 150 characters"><?=html_entity_decode($obj->task_description)?></textarea>
		</td>
	</tr>
	</table>
</td>
</tr>
</table>
</form>

<script>
function selectItem(cb, e){
	cb.parentNode.parentNode.className = cb.checked ? 'active' : 'second';
	if (e != undefined) {
		var s = $('idContribute_' + cb.value);
		if (s != null) s.disabled = !cb.checked;
		doCalcEffort();
	}
}

var hdays = [];
<?
	foreach ($holidays as $d => $s) {
		echo "hdays[Date.parse('".str_replace('-', '/', $d)."')] = true;\n";
	}
?>

function doCheckDate(f)
{
	var fd = Date.parseDate($('idDateFrom').value, '<?=FMT_TIMESTAMP_DATE?>');
	var td = Date.parseDate($('idDateTo').value, '<?=FMT_TIMESTAMP_DATE?>');

	if (fd > td) {
		alert("You just set Start date after End date. System will be set Start date equal End date");
		if (f.id == 'idDateFrom') {
			$('idDateTo').value = $('idDateFrom').value;
			$('idDateToD').value = fd.print('<?=$df?>');
		}
		else {
			$('idDateFrom').value = $('idDateTo').value;
			$('idDateFromD').value = td.print('<?=$df?>');
		}
	}

	changeProject($('task_item_id').value);
}

function doCalcDuration()
{
	var d = $('idDuration');
	var fd = Date.parseDate($('idDateFromD').value, '<?=$df?>');
	var td = Date.parseDate($('idDateToD').value, '<?=$df?>');
	var h, t = parseInt('<?=$dPconfig['daily_working_hours']?>', 10);
	var wdays = '<?=$dPconfig['cal_working_days']?>';
	var msec_per_day = Date.DAY;

	if (t == 0 || t == NaN) t = 8;
	h = t * (((td - fd) / msec_per_day) + 1);
	while (fd <= td) {
		var z = wdays.indexOf(fd.getDay());
		if (z < 0 || (z % 2 == 1) || hdays[fd.getTime()]) h -= t;
		fd.setTime(fd.getTime() + msec_per_day);
	}
	d.value = h;
	doCalcEffort();
}

var uids = [<?=implode(',', array_keys($resourceList))?>];

function doCalcEffort()
{
	var e = 0.0;
	var d = $('idDuration').value.trim();
	if (d == '') return;
	d = parseFloat(d);
	for (i in uids) {
		var c = $('idContribute_'+uids[i]);
		if (c.disabled) continue;
		e += d * parseInt(c.value, 10) / 100;
	}
	$('idEffort').value = e;
}

function doInitEffortHandlers()
{
	for (i in uids) {
		var c = $('idContribute_'+uids[i]);
		c.onchange = doCalcEffort;
	}
	doCalcEffort();
}

//setTimeout('doInitEffortHandlers()', 150);
</script>

<div id="validation_rules" style="visibility: hidden; display: none">
	var fidTaskItemCode = new LiveValidation('task_item_autocompleter');
	fidTaskItemCode.add( Validate.Presence);

	var fidTaskItemName = new LiveValidation('idTaskItemName');
	fidTaskItemName.add( Validate.Presence);

	var fidTaskFigure = new LiveValidation('idTaskFigure');
	fidTaskFigure.add( Validate.Presence);
	fidTaskFigure.add( Validate.Numericality, {minimum: 1, maximum: 999999999999} );

	var ftask_location = new LiveValidation('task_location');
	ftask_location.add( Validate.Presence);
	ftask_location.add( Validate.Length, {maximum: 150});

	var idTaskUnit = new LiveValidation('idTaskUnit');
	idTaskUnit.add(Validate.Presence);

	var idDateFromD = new LiveValidation('idDateFromD');
	idDateFromD.add( Validate.Presence);

	var idDateToD = new LiveValidation('idDateToD');
	idDateToD.add( Validate.Presence);

	var idTaskDivision = new LiveValidation('idTaskDivision');
	idTaskDivision.add( Validate.Presence);

	var task_costcenter = new LiveValidation('task_costcenter');
	task_costcenter.add( Validate.Presence);

	var task_resource = new LiveValidation('task_resource');
	task_resource.add( Validate.Presence);

	var task_remarks = new LiveValidation('task_remarks');
	task_remarks.add( Validate.Length, {maximum: 150});

	new Tips($$('.text'));
</div>
<script type="text/javascript" language="javascript">
	eval($('validation_rules').innerHTML);

	function init() {
		changeProject($('task_item_id').value);
		<? if ($task_id > 0) { ?>
		changeQuotation($('task_quotation'), <?=@$obj->task_quotation?>);
		<? } ?>
	}

	setTimeout('init()', 250);
</script>
